<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Balance;
use App\Models\MallRefund;
use App\Models\UnionOrder;
use Illuminate\Http\Request;

class FundController extends BaseController
{

    public $model = UnionOrder::class;


    public function index(Request $request) {
        $input = $request->input();
        $search = ['order_sn' => '', 'type' => '', 'start_at' => '', 'end_at' => ''];
        $users = UnionOrder::apply($search, $input)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        return $this->paginate($users);
    }

    public function refund(Request $request) {
        $input = $request->input();
        $search = ['status' => 6];
        $is_return_product = $request->input('is_return_product', -1);
        $refund_sn = $request->input('refund_sn');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');

        $list = MallRefund::apply($search, $input)
                ->select(['paid_end_at', 'paid_amount', 'is_return_product', 'refund_sn', 'status'])->when($is_return_product != -1, function ($q) use($is_return_product){
                    $q->where('is_return_product', $is_return_product);
                })->when($refund_sn, function ($q) use($refund_sn){
                    $q->where('refund_sn', 'like', '%' . $refund_sn . '%');
                });

        if ($start_at)
            $list = $list->where('paid_end_at', '>=', $start_at);

        if ($end_at) {
            $end_at = date('Y-m-d', strtotime($end_at) + 24 * 3600);
            $list = $list->where('paid_end_at', '<', $end_at);
        }

        $list = $list->orderBy('id', 'desc')
            ->paginate(\request('per_page', 20));
        return $this->paginate($list);
    }

    public function commission(Request $request) {
        $input = $request->input();
        $search = [
            'start_at' => '',
            'end_at' => '',
            'order_sn' => ''
        ];
        $type = $request->input('type');
        $all = [Balance::TYPE_MALL, Balance::TYPE_VIP];
        if ($type && !in_array($type, $all))
            return $this->failed('status 参数值有误');
        if (!$type) {
            $type = $all;
        } else {
            $type = [$type];
        }
        $list = Balance::whereIn('type', $type)->apply($search, $input)->withCertain('user', ['nickname'])
            ->orderBy('id', 'desc')->paginate(per_page());
        return $this->paginate($list);
    }

}

